package com.chs.students.conf;



import com.chs.students.entity.Menu;
import com.chs.students.entity.Role;
import com.chs.students.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/****
 * @Author:Chs
 * @Description:权限配置
 * @Date 2020/11/28 10:35
 *****/
@Component
public class CustomFilterInvocationSecurityMetadataSource
        implements FilterInvocationSecurityMetadataSource {
    //用来实现ant风格的URL匹配
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Autowired
    MenuMapper menuMapper;

    /***
     * 表示当前请求的URL所需的角色
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object)
            throws IllegalArgumentException {
        //从参数中提取当前的URL请求
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        //从数据库获取menu表的信息
        List<Menu> allMenus = menuMapper.getAllMenus();
        /**
         * 遍历过程中获取当前请求的URL所需角色信息并返回
         */
        for (Menu menu : allMenus) {
            if (antPathMatcher.match(menu.getPattern(), requestUrl)) {
                List<Role> roles = menu.getRoles();
                String[] roleArr = new String[roles.size()];
                for (int i = 0; i < roleArr.length; i++) {
                    roleArr[i] = roles.get(i).getName();
                }
                //返回所需角色
                return SecurityConfig.createList(roleArr);
            }
        }
        //若找不到角色，则返回登录后即可访问的ROLE_LOGIN
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    //校验相关配置是否正确
    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    //返回类对象是否支持校验
    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
